package com.yuke.cloud.service.tmc.util;

import com.yuke.cloud.service.tmc.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.util.LinkedList;
import java.util.Map;
@Slf4j
public class MyChannelInterceptor implements ChannelInterceptor {

    @SuppressWarnings("rawtypes")
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            //判断是否是首次连接请求
            log.info(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            log.info(raw.toString());
            if (raw instanceof Map) {
                Object name = ((Map) raw).get("name");
                if (name instanceof LinkedList) {
                    //设置当前访问器的认证用户
//                    log.info(((LinkedList)name).get(0).toString());
                    accessor.setUser(new User(((LinkedList)name).get(0).toString()));
                }
            }
        } else if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {
            log.info("连接断开------" + message.getHeaders().size());
            //点击断开连接，这里会执行两次，第二次执行的时候，message.getHeaders.size()=5,第一次是6。直接关闭浏览器，只会执行一次，size是5。
            User user = (User) message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            //  如果同时发生两个连接，只有都断开才能叫做不在线
        }
        //不是首次连接，已经成功登录
        return message;
    }
}
